#!/usr/bin/env node
/**
 * MCP SSH工具 - Web界面服务器
 * 提供Web界面来管理SSH服务器
 */

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
const fs = require('fs');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件配置
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// 配置文件路径
const CONFIG_PATH = path.join(__dirname, 'config', 'servers.json');

// 确保配置目录存在
const configDir = path.dirname(CONFIG_PATH);
if (!fs.existsSync(configDir)) {
    fs.mkdirSync(configDir, { recursive: true });
}

// 如果配置文件不存在，创建默认配置
if (!fs.existsSync(CONFIG_PATH)) {
    const defaultConfig = {
        servers: []
    };
    fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaultConfig, null, 2));
}

// 读取服务器配置
function readServers() {
    try {
        const data = fs.readFileSync(CONFIG_PATH, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        console.error('读取配置文件失败:', error);
        return { servers: [] };
    }
}

// 保存服务器配置
function saveServers(config) {
    try {
        fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));
        return true;
    } catch (error) {
        console.error('保存配置文件失败:', error);
        return false;
    }
}

// API路由

// 获取所有服务器
app.get('/api/servers', (req, res) => {
    try {
        const config = readServers();
        // 隐藏敏感信息
        const safeServers = config.servers.map(server => {
            const safeServer = { ...server };
            if (safeServer.password) {
                safeServer.password = '******';
            }
            return safeServer;
        });
        res.json({ success: true, servers: safeServers });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 添加服务器
app.post('/api/servers', (req, res) => {
    try {
        const { name, ip, port, username, auth_type, password, key_path, description } = req.body;
        
        if (!name || !ip || !username || !auth_type) {
            return res.status(400).json({ 
                success: false, 
                error: '缺少必要参数' 
            });
        }
        
        const config = readServers();
        const newServer = {
            name,
            ip,
            port: port || 22,
            username,
            auth_type,
            password: auth_type === 'password' ? password : undefined,
            key_path: auth_type === 'key' ? key_path : undefined,
            description: description || ''
        };
        
        config.servers.push(newServer);
        
        if (saveServers(config)) {
            res.json({ success: true, message: '服务器添加成功', server: newServer });
        } else {
            res.status(500).json({ success: false, error: '保存配置失败' });
        }
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 删除服务器
app.delete('/api/servers/:name', (req, res) => {
    try {
        const { name } = req.params;
        const config = readServers();
        const serverIndex = config.servers.findIndex(s => s.name === name);
        
        if (serverIndex === -1) {
            return res.status(404).json({ success: false, error: '服务器不存在' });
        }
        
        config.servers.splice(serverIndex, 1);
        
        if (saveServers(config)) {
            res.json({ success: true, message: '服务器删除成功' });
        } else {
            res.status(500).json({ success: false, error: '保存配置失败' });
        }
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 获取服务器信息
app.get('/api/servers/:name', (req, res) => {
    try {
        const { name } = req.params;
        const config = readServers();
        const server = config.servers.find(s => s.name === name);
        
        if (!server) {
            return res.status(404).json({ success: false, error: '服务器不存在' });
        }
        
        // 隐藏敏感信息
        const safeServer = { ...server };
        if (safeServer.password) {
            safeServer.password = '******';
        }
        
        res.json({ success: true, server: safeServer });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 测试连接
app.post('/api/test-connection', (req, res) => {
    try {
        const { server_name } = req.body;
        
        if (!server_name) {
            return res.status(400).json({ 
                success: false, 
                error: '缺少服务器名称' 
            });
        }
        
        // 调用Python SSH服务器进行真实的连接测试
        const { spawn } = require('child_process');
        const pythonProcess = spawn('python', ['mcp/ssh_server.py', 'test_connection', server_name]);
        
        let output = '';
        let errorOutput = '';
        
        pythonProcess.stdout.on('data', (data) => {
            output += data.toString();
        });
        
        pythonProcess.stderr.on('data', (data) => {
            errorOutput += data.toString();
        });
        
        pythonProcess.on('close', (code) => {
            if (code === 0) {
                try {
                    const result = JSON.parse(output);
                    res.json(result);
                } catch (e) {
                    res.json({ 
                        success: true, 
                        message: `与服务器 ${server_name} 的连接测试成功` 
                    });
                }
            } else {
                res.json({ 
                    success: false, 
                    error: `连接测试失败: ${errorOutput || '未知错误'}` 
                });
            }
        });
        
        pythonProcess.on('error', (err) => {
            res.status(500).json({ 
                success: false, 
                error: `启动Python进程失败: ${err.message}` 
            });
        });
        
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 执行命令
app.post('/api/execute-command', (req, res) => {
    try {
        const { server_name, command } = req.body;
        
        if (!server_name || !command) {
            return res.status(400).json({ 
                success: false, 
                error: '缺少必要参数' 
            });
        }
        
        // 调用Python SSH服务器执行真实的SSH命令
        const { spawn } = require('child_process');
        const pythonProcess = spawn('python', ['mcp/ssh_server.py', 'execute_command', server_name, command]);
        
        let output = '';
        let errorOutput = '';
        
        pythonProcess.stdout.on('data', (data) => {
            output += data.toString();
        });
        
        pythonProcess.stderr.on('data', (data) => {
            errorOutput += data.toString();
        });
        
        pythonProcess.on('close', (code) => {
            if (code === 0) {
                try {
                    const result = JSON.parse(output);
                    res.json(result);
                } catch (e) {
                    res.json({ 
                        success: true, 
                        output: output || '命令执行成功',
                        error: errorOutput || null
                    });
                }
            } else {
                res.json({ 
                    success: false, 
                    error: `命令执行失败: ${errorOutput || '未知错误'}` 
                });
            }
        });
        
        pythonProcess.on('error', (err) => {
            res.status(500).json({ 
                success: false, 
                error: `启动Python进程失败: ${err.message}` 
            });
        });
        
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 主页路由
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`🚀 MCP SSH工具Web界面已启动`);
    console.log(`📖 访问地址: http://localhost:${PORT}`);
    console.log(`🔧 MCP服务: 使用 mcp/mcp_protocol_server.py`);
    console.log(`⏹️  按 Ctrl+C 停止服务器`);
});

// 优雅关闭
process.on('SIGINT', () => {
    console.log('\n🛑 正在关闭服务器...');
    process.exit(0);
}); 